package com.lifeverse.factory;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.ConsciousnessLevel;
import com.lifeverse.entity.enums.LifeEntityStatus;
import com.lifeverse.entity.enums.LifeEntityType;
import com.lifeverse.factory.type.*;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 生命体工厂类
 * 负责创建不同类型的生命体实例
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LifeEntityFactory {
    
    private final CorporateLifeEntityCreator corporateCreator;
    private final UrbanLifeEntityCreator urbanCreator;
    private final ConceptualLifeEntityCreator conceptualCreator;
    private final HybridLifeEntityCreator hybridCreator;
    private final IndividualLifeEntityCreator individualCreator;
    private final SystemLifeEntityCreator systemCreator;
    
    /**
     * 创建生命体
     * 
     * @param type 生命体类型
     * @param name 生命体名称
     * @param description 生命体描述
     * @param configuration 配置参数
     * @return 创建的生命体实例
     */
    public LifeEntity createLifeEntity(LifeEntityType type, String name, String description, Map<String, Object> configuration) {
        log.info("Creating life entity of type: {} with name: {}", type, name);
        
        LifeEntity lifeEntity = switch (type) {
            case CORPORATE -> corporateCreator.create(name, description, configuration);
            case URBAN -> urbanCreator.create(name, description, configuration);
            case CONCEPTUAL -> conceptualCreator.create(name, description, configuration);
            case HYBRID -> hybridCreator.create(name, description, configuration);
            case INDIVIDUAL -> individualCreator.create(name, description, configuration);
            case SYSTEM -> systemCreator.create(name, description, configuration);
        };
        
        // 设置通用属性
        setupCommonProperties(lifeEntity, type, name, description, configuration);
        
        log.info("Successfully created life entity: {} of type: {}", name, type);
        return lifeEntity;
    }
    
    /**
     * 创建混合生命体（从多个现有生命体融合）
     * 
     * @param name 混合生命体名称
     * @param description 描述
     * @param sourceEntities 源生命体列表
     * @param fusionConfiguration 融合配置
     * @return 混合生命体实例
     */
    public LifeEntity createHybridLifeEntity(String name, String description, 
                                           java.util.List<LifeEntity> sourceEntities, 
                                           Map<String, Object> fusionConfiguration) {
        log.info("Creating hybrid life entity: {} from {} source entities", name, sourceEntities.size());
        
        LifeEntity hybridEntity = hybridCreator.createFromFusion(name, description, sourceEntities, fusionConfiguration);
        
        // 设置混合生命体特有属性
        setupHybridProperties(hybridEntity, sourceEntities, fusionConfiguration);
        
        log.info("Successfully created hybrid life entity: {}", name);
        return hybridEntity;
    }
    
    /**
     * 克隆生命体（创建相似的生命体）
     * 
     * @param originalEntity 原始生命体
     * @param newName 新生命体名称
     * @param variationLevel 变异程度（0.0-1.0）
     * @return 克隆的生命体实例
     */
    public LifeEntity cloneLifeEntity(LifeEntity originalEntity, String newName, double variationLevel) {
        log.info("Cloning life entity: {} to create: {} with variation level: {}", 
                originalEntity.getName(), newName, variationLevel);
        
        LifeEntity clonedEntity = switch (originalEntity.getType()) {
            case CORPORATE -> corporateCreator.clone(originalEntity, newName, variationLevel);
            case URBAN -> urbanCreator.clone(originalEntity, newName, variationLevel);
            case CONCEPTUAL -> conceptualCreator.clone(originalEntity, newName, variationLevel);
            case HYBRID -> hybridCreator.clone(originalEntity, newName, variationLevel);
            case INDIVIDUAL -> individualCreator.clone(originalEntity, newName, variationLevel);
            case SYSTEM -> systemCreator.clone(originalEntity, newName, variationLevel);
        };
        
        // 设置克隆特有属性
        setupCloneProperties(clonedEntity, originalEntity, variationLevel);
        
        log.info("Successfully cloned life entity: {}", newName);
        return clonedEntity;
    }
    
    /**
     * 设置通用属性
     */
    private void setupCommonProperties(LifeEntity lifeEntity, LifeEntityType type, String name, 
                                     String description, Map<String, Object> configuration) {
        lifeEntity.setType(type);
        lifeEntity.setName(name);
        lifeEntity.setDescription(description);
        lifeEntity.setStatus(LifeEntityStatus.CREATING);
        lifeEntity.setConsciousnessLevel(ConsciousnessLevel.INITIAL);
        lifeEntity.setBirthTime(LocalDateTime.now());
        lifeEntity.setLastActiveAt(LocalDateTime.now());
        lifeEntity.setEvolutionCount(0);
        
        // 设置配置信息
        if (configuration != null && !configuration.isEmpty()) {
            lifeEntity.setConfiguration(JsonUtils.toJson(configuration));
        }
        
        // 设置初始元数据
        Map<String, Object> metadata = Map.of(
                "createdBy", "LifeEntityFactory",
                "creationMethod", "factory",
                "version", "1.0",
                "capabilities", getTypeCapabilities(type)
        );
        lifeEntity.setMetadata(JsonUtils.toJson(metadata));
    }
    
    /**
     * 设置混合生命体属性
     */
    private void setupHybridProperties(LifeEntity hybridEntity, java.util.List<LifeEntity> sourceEntities, 
                                     Map<String, Object> fusionConfiguration) {
        // 计算融合后的属性值
        BigDecimal avgWisdom = sourceEntities.stream()
                .map(LifeEntity::getWisdomScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(BigDecimal.valueOf(sourceEntities.size()), 2, java.math.RoundingMode.HALF_UP);
        
        BigDecimal avgCreativity = sourceEntities.stream()
                .map(LifeEntity::getCreativityScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(BigDecimal.valueOf(sourceEntities.size()), 2, java.math.RoundingMode.HALF_UP);
        
        BigDecimal avgCollaboration = sourceEntities.stream()
                .map(LifeEntity::getCollaborationScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(BigDecimal.valueOf(sourceEntities.size()), 2, java.math.RoundingMode.HALF_UP);
        
        // 应用融合加成（混合生命体通常具有更高的能力）
        double fusionBonus = 1.2; // 20%的融合加成
        hybridEntity.setWisdomScore(avgWisdom.multiply(BigDecimal.valueOf(fusionBonus)));
        hybridEntity.setCreativityScore(avgCreativity.multiply(BigDecimal.valueOf(fusionBonus)));
        hybridEntity.setCollaborationScore(avgCollaboration.multiply(BigDecimal.valueOf(fusionBonus)));
        
        // 设置融合元数据
        Map<String, Object> fusionMetadata = Map.of(
                "sourceEntityIds", sourceEntities.stream().map(LifeEntity::getId).toList(),
                "sourceEntityTypes", sourceEntities.stream().map(entity -> entity.getType().name()).toList(),
                "fusionTime", LocalDateTime.now(),
                "fusionConfiguration", fusionConfiguration
        );
        
        Map<String, Object> existingMetadata = JsonUtils.fromJson(hybridEntity.getMetadata(), Map.class);
        existingMetadata.put("fusion", fusionMetadata);
        hybridEntity.setMetadata(JsonUtils.toJson(existingMetadata));
    }
    
    /**
     * 设置克隆属性
     */
    private void setupCloneProperties(LifeEntity clonedEntity, LifeEntity originalEntity, double variationLevel) {
        // 设置父生命体ID
        clonedEntity.setParentId(originalEntity.getId());
        
        // 应用变异到属性值
        applyVariation(clonedEntity, originalEntity, variationLevel);
        
        // 设置克隆元数据
        Map<String, Object> cloneMetadata = Map.of(
                "originalEntityId", originalEntity.getId(),
                "originalEntityName", originalEntity.getName(),
                "cloneTime", LocalDateTime.now(),
                "variationLevel", variationLevel,
                "cloneGeneration", getCloneGeneration(originalEntity) + 1
        );
        
        Map<String, Object> existingMetadata = JsonUtils.fromJson(clonedEntity.getMetadata(), Map.class);
        existingMetadata.put("clone", cloneMetadata);
        clonedEntity.setMetadata(JsonUtils.toJson(existingMetadata));
    }
    
    /**
     * 应用变异到克隆生命体
     */
    private void applyVariation(LifeEntity clonedEntity, LifeEntity originalEntity, double variationLevel) {
        // 对各项能力值应用变异
        clonedEntity.setWisdomScore(applyVariationToScore(originalEntity.getWisdomScore(), variationLevel));
        clonedEntity.setCreativityScore(applyVariationToScore(originalEntity.getCreativityScore(), variationLevel));
        clonedEntity.setCollaborationScore(applyVariationToScore(originalEntity.getCollaborationScore(), variationLevel));
        clonedEntity.setEnergyLevel(applyVariationToScore(originalEntity.getEnergyLevel(), variationLevel));
        clonedEntity.setHealthScore(applyVariationToScore(originalEntity.getHealthScore(), variationLevel));
    }
    
    /**
     * 对单个分数应用变异
     */
    private BigDecimal applyVariationToScore(BigDecimal originalScore, double variationLevel) {
        // 生成-1到1之间的随机变异因子
        double variationFactor = (Math.random() - 0.5) * 2 * variationLevel;
        BigDecimal variation = originalScore.multiply(BigDecimal.valueOf(variationFactor * 0.2)); // 最大20%变异
        BigDecimal newScore = originalScore.add(variation);
        
        // 确保分数在合理范围内
        if (newScore.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.ZERO;
        }
        if (newScore.compareTo(BigDecimal.valueOf(1000)) > 0) {
            return BigDecimal.valueOf(1000);
        }
        
        return newScore;
    }
    
    /**
     * 获取类型特有能力
     */
    private java.util.List<String> getTypeCapabilities(LifeEntityType type) {
        return switch (type) {
            case CORPORATE -> java.util.List.of("business_strategy", "resource_management", "market_analysis", "stakeholder_management");
            case URBAN -> java.util.List.of("infrastructure_management", "citizen_services", "urban_planning", "sustainability");
            case CONCEPTUAL -> java.util.List.of("abstract_thinking", "concept_evolution", "knowledge_synthesis", "innovation");
            case HYBRID -> java.util.List.of("multi_domain_expertise", "synergy_creation", "adaptive_integration", "complex_problem_solving");
            case INDIVIDUAL -> java.util.List.of("personal_growth", "skill_development", "social_interaction", "self_reflection");
            case SYSTEM -> java.util.List.of("process_optimization", "automation", "system_integration", "performance_monitoring");
        };
    }
    
    /**
     * 获取克隆代数
     */
    private int getCloneGeneration(LifeEntity entity) {
        try {
            Map<String, Object> metadata = JsonUtils.fromJson(entity.getMetadata(), Map.class);
            if (metadata.containsKey("clone")) {
                Map<String, Object> cloneInfo = (Map<String, Object>) metadata.get("clone");
                return (Integer) cloneInfo.getOrDefault("cloneGeneration", 0);
            }
        } catch (Exception e) {
            log.warn("Failed to parse clone generation from metadata for entity: {}", entity.getId());
        }
        return 0;
    }
}